package synchronization;

import java.util.ArrayList;

public class SharedQueue<T> {
	private ArrayList<T> queue;
	private int capacity;
	
	public SharedQueue(int capacity) {
		queue = new ArrayList<T>();
		this.capacity = capacity;
	}
	
	/**
	 * Appends given resource to the end of the queue and if the
	 * queue is full, blocks until some space is available.
	 */
	public void enqueue(T resource) throws InterruptedException {
		synchronized (queue) {
			while (queue.size() == capacity) {
				queue.wait();
			}
			queue.add(resource);
			queue.notify();		
		}
	}
	
	/**
	 * Gets the next resource from the queue and if the queue is
	 * empty blocks until some resource arrive.
	 */
	public T dequeue() throws InterruptedException {
		synchronized (queue) {
			while (queue.size() == 0) {
				queue.wait();
			}
			queue.notify();
			T resource = queue.remove(0);
			return resource;
		}
	}
	
	public void printState() {
		System.out.printf("Queue state: %d of %d\n",
			queue.size(), this.capacity);		
	}
}
